package alva.com.getcamera.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.util.Pools;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

import alva.com.getcamera.bean.ImageBean;
import uk.co.senab.photoview.PhotoView;

/**
 * Created by Administrator on 2016/11/8 0008.
 */
public class PhotoViewPagerAdapter extends PagerAdapter {
    private Context context;
    private ArrayList<ImageBean> imageList;
    private Pools.Pool<PhotoView> pool = new Pools.SimplePool<>(4);

    public PhotoViewPagerAdapter(Context context, ArrayList<ImageBean> imageList) {
        this.context = context;
        this.imageList = imageList;
    }

    @Override
    public int getCount() {
        return imageList.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view.equals(object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ImageBean imageBean = imageList.get(position);
        PhotoView photoView = pool.acquire();
        if (photoView == null) {
            photoView = new PhotoView(context);
            photoView.setAdjustViewBounds(true);
        }
        photoView.setImageBitmap(getBitmap(imageBean.getImagePath()));
        container.addView(photoView);
        return photoView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
        pool.release((PhotoView) object);
    }

    public void addAll(ArrayList<ImageBean> list) {
        imageList.addAll(list);
        notifyDataSetChanged();
    }

    public void clear() {
        imageList.clear();
        notifyDataSetChanged();
    }

    public void add(ImageBean imageBean) {
        imageList.add(imageBean);
        notifyDataSetChanged();
    }

    public void add(int i, ImageBean imageBean) {
        imageList.add(i, imageBean);
        notifyDataSetChanged();
    }

    private Bitmap getBitmap(final String imagePath) {
        final Bitmap[] bitmap = {null};
        new Thread() {
            @Override
            public void run() {
                bitmap[0] = BitmapFactory.decodeFile(imagePath);
            }
        }.run();
        return bitmap[0];
    }
}
